package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.config.HuanxinConfig;
import com.itheima.appserver.excepiton.BusinessException;
import com.itheima.appserver.excepiton.ErrorResult;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.pojo.domain.Announcement;
import com.itheima.commons.pojo.mongo.Comment;
import com.itheima.commons.pojo.domain.UserInfo;
import com.itheima.commons.pojo.mongo.Users;
import com.itheima.commons.vo.reception.*;
import com.itheima.dubbo.interfaces.*;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yaohu
 * @date 2021/12/12
 * @Version 1.0
 * @describe
 */
@Service
public class IMService {

    @Reference
    private UsersApi usersApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private CommentApi commentApi;

    @Reference
    private AnnouncementApi announcementApi;

    @Autowired
    private MyCenterService myCenterService;

    @Autowired
    private HuanxinConfig huanxinConfig;

    @Autowired
    private RequestService requestService;

    /**
     * 根据环信用户名查询用户信息
     *
     * @param userName
     * @return
     */
    public UserInfoVo queryUserInfoByUserName(String userName) {
        return myCenterService.queryUserInfoByUserId(Convert.toLong(StrUtil.subAfter(userName, "_", true)));
    }

    /**
     * 添加好友 点击聊一下
     *
     * @param friendId
     */
    public void contactUser(Long friendId) {
        // 1.往好友表中添加两条数据
        Users users = new Users();
        users.setId(new ObjectId());
        users.setUserId(UserThreadLocal.getUserId());
        users.setFriendId(friendId);
        users.setDate(System.currentTimeMillis());
        usersApi.addUsers(users);

        Users users1 = new Users();
        users1.setId(new ObjectId());
        users1.setUserId(friendId);
        users1.setFriendId(UserThreadLocal.getUserId());
        users1.setDate(System.currentTimeMillis());
        usersApi.addUsers(users1);

        // 2.给环信发送请求 让环信把两人绑定为好友
        // /{org_name}/{app_name}/users/{owner_username}/contacts/users/{friend_username}
        HttpResponse response = requestService.execute(huanxinConfig.getUrl() + huanxinConfig.getOrgName()
                + "/" + huanxinConfig.getAppName() + "/users/HX_" + users.getUserId()
                + "/contacts/users/HX_" + users1.getUserId(), null, Method.POST);
        if (!response.isOk()) {
            throw new BusinessException(ErrorResult.addFriendError());
        }
    }

    /**
     * 删除好友
     *
     * @param userId
     */
    public void removeContactUser(Long userId) {
        // 1.删除好友表记录
        usersApi.removeUser(UserThreadLocal.getUserId(), userId);
        usersApi.removeUser(userId, UserThreadLocal.getUserId());
        // 2.删除环信好友
        // /{org_name}/{app_name}/users/{owner_username}/contacts/users/{friend_username}
        HttpResponse response = requestService.execute(huanxinConfig.getUrl() + huanxinConfig.getOrgName() + "/"
                + huanxinConfig.getAppName() + "/users/HX_" + UserThreadLocal.getUserId() + "/contacts/users/HX_" + userId,
                null, Method.DELETE);
        if (!response.isOk()) {
            throw new BusinessException(ErrorResult.removeFriendError());
        }
    }

    /**
     * 查询联系人列表
     *
     * @param page     分页页码
     * @param pageSize 页面条数
     * @param keyword  关键词的搜索  如果关键词不为空 我们要查询全部好友并且根据关键词过滤  如果没有关键词 我们做分页
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        // 1.查询好友列表
        List<Users> usersList = usersApi.findUsersByUserId(UserThreadLocal.getUserId(), page, pageSize, keyword);
        // 2.获取好友id
        List<Long> friendIds = CollUtil.getFieldValues(usersList, "friendId", Long.class);
        // 3.根据好友id查询好友信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findUserInfoByUserIds(UserInfo.builder().nickName(keyword).build(), friendIds);

        List<UsersVo> usersVos = new ArrayList<>();
        for (UserInfo info : userInfoMap.values()) {
            UsersVo usersVo = new UsersVo();
            // 用户ID
            usersVo.setId(info.getUserId());
            // 环信ID
            usersVo.setUserId("HX_" + info.getUserId());
            usersVo.setAvatar(info.getLogo());
            usersVo.setNickname(info.getNickName());
            usersVo.setGender(info.getSex() == 1 ? "man" : "woman");
            usersVo.setAge(info.getAge());
            usersVo.setCity(StrUtil.subBefore(info.getCity(), "-", false));

            usersVos.add(usersVo);
        }
        return new PageResult(page, pageSize, 0L, usersVos);
    }

    /**
     * 分页查询评论列表
     *
     * @param page
     * @param pageSize
     * @param commentType
     * @return
     */
    public PageResult queryCommentList(Integer page, Integer pageSize, int commentType) {
        // 分页查询点赞/评论/喜欢列表
        List<Comment> commentList = commentApi.queryCommentListByUserId(page, pageSize, UserThreadLocal.getUserId(), commentType);
        // 获取发布评论人的id
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        // 查询发布人信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findUserInfoByUserIds(userIds);
        // 拼凑vo对象
        List<MessageCommentVo> voList = new ArrayList<>();
        for (Comment comment : commentList) {
            MessageCommentVo vo = new MessageCommentVo();
            UserInfo userInfo = userInfoMap.get(comment.getUserId());
            vo.setId(userInfo.getUserId().toString());
            vo.setAvatar(userInfo.getLogo());
            vo.setNickname(userInfo.getNickName());
            vo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
            voList.add(vo);
        }
        return new PageResult(page, pageSize, 0L, voList);
    }

    /**
     * 分页查询公告列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {

        List<Announcement> announcementList = announcementApi.findAnnouncementByPage(page, pageSize);
        ArrayList<AnnouncementVo> voList = new ArrayList<>();

        for (Announcement announcement : announcementList) {
            AnnouncementVo vo = new AnnouncementVo();

            vo.setId(announcement.getId().toString());
            vo.setTitle(announcement.getTitle());
            vo.setDescription(announcement.getDescription());
            vo.setCreateDate(DateUtil.format(announcement.getCreated(), "yyyy-MM-dd HH:mm"));

            voList.add(vo);
        }
        return new PageResult(page, pageSize, 0L, voList);
    }
}
